import { TagOutlined } from '@ant-design/icons';
import { ModalForm, ProFormInstance } from '@ant-design/pro-components';
import { Button, Form, Input, SelectProps, Tag } from 'antd';
import { FormInstance } from 'rc-field-form';
import React, { useEffect, useRef, useState } from 'react';

type IOptionsSelectorProps = {
  value?: {[key: string]: {
    text: string;
    status: any;
  }};
  onChange?: (val: any) => void;
};

export default function OptionsSelector({
  value = {},
  onChange = () => {},
}: IOptionsSelectorProps) {
  const [modalFormVisible, setModalFormVisible] = useState(false);
  const modalFormRef = useRef<ProFormInstance>();

  const handleFinish = async (formData: any) => {
    onChange({
      ...value,
      [formData.name]: {
        text: formData.text,
        status: formData.status,
      },
    });

    return true;
  };

  const showModalForm = () => {
    setModalFormVisible(true);
  };

  const hideModalForm = () => {
    setModalFormVisible(false);
  };

  useEffect(() => {
    return () => {
      if (!modalFormVisible) return;
      modalFormRef.current?.resetFields();
    };
  }, [modalFormVisible]);

  return (
    <>
      {Object.keys(value).map((key: string) => (
        <Tag closable>{value[key].text}</Tag>
      ))}

      <ModalForm
        onTouchCancelCapture={hideModalForm}
        // visible={modalFormVisible}
        trigger={
          <Button type="primary" size="small" onClick={showModalForm}>
            添加
          </Button>
        }
        title="添加候选项"
        layout="horizontal"
        formRef={modalFormRef}
        labelCol={{ span: 4 }}
        onFinish={handleFinish}
        onTouchCancel={hideModalForm}
      >
        <Form.Item label="名称" name="name" rules={[{ required: true }]}>
          <Input placeholder="请输入英文单词名称" />
        </Form.Item>
        <Form.Item label="标题" name="text" rules={[{ required: true }]}>
          <Input placeholder="请输入标题" />
        </Form.Item>
        <Form.Item label="值" name="status" rules={[{ required: true }]}>
          <Input placeholder="请输入值" />
        </Form.Item>
      </ModalForm>
    </>
  );
}
